// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
import CustomerData from '../CustomerData'
import UserData from '../UserData'
cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
        descTitle: {
            type: cc.Label,
            default: null
        },
        descContent: {
            type: cc.RichText,
            default: null
        },
        descPic: {
            type: cc.Sprite,
            default: null,
        },
        customerList: {
            type: cc.Node,
            default: null
        },
        customerSPAtlas: {
            type: cc.SpriteAtlas,
            default: null
        },
        chefSPAtlas: {
            type: cc.SpriteAtlas,
            default: null
        },
        customerPrefab: {
            type: cc.Prefab,
            default: null
        },
        shareBtn: cc.Node,
        poweredBy: cc.Node,
        conditionDesc: cc.Node,
        isShowChef: true,
        switchText: cc.Label,
    },
    showPoweredBy(name, avatarUrl) {
        this.poweredBy.active = true
        let nickname = this.poweredBy.getChildByName('nickname').getComponent(cc.Label)
        let avatar = this.poweredBy.getChildByName('avatar').getComponent(cc.Sprite)
        nickname.string = name
        cc.loader.load({
            url: avatarUrl, type: 'png'
        }, (err, texture) => {
            if (err) console.error(err);
            avatar.spriteFrame = new cc.SpriteFrame(texture);
        });
    },
    initActive() {
        this.descContent.string = ''
        this.descPic.enabled = false
        this.shareBtn.active = false
        this.poweredBy.active = false
        this.conditionDesc.active = false
    },
    handleClick(event, data) {
        var animCtrl = event.target.getComponent(cc.Animation)
        
        this.initActive()

        animCtrl.play()
        
        if (data.type === 'CHEF') {
            this.descContent.active = true
            this.descPic.enabled = true

            this.descTitle.string = data.name
            this.descContent.string = '<color=#5D1F04>' + data.story + '</color>'
            this.descPic.spriteFrame = data.atlas.getSpriteFrame(data.id)
        } else if (UserData.acquiredCustomersList && UserData.acquiredCustomersList.includes(data.id)) {
            this.descContent.active = true
            this.descPic.enabled = true

            this.descTitle.string = data.name
            this.descContent.string = '<color=#5D1F04>' + data.story + '</color>'
            this.descPic.spriteFrame = data.atlas.getSpriteFrame(data.id)
            UserData.acquiredCustomerSharedDetail.forEach(item => {
                if (item.data === data.id) {
                    this.showPoweredBy(item.wechatNickname, item.wechatAvatarUrl)
                }
            })

        } else {
            this.descTitle.string = '获得方法'
            switch (data.condition) {
                case 'money':
                    this.conditionDesc.active = true
                    this.conditionDesc.getComponent('labelFixedRichText').setNumber(data.conditionValue, '<color=#5D1F04>累计获得:</color><color=#ff0000>', '</color><color=#5D1F04> 金币</color>')
                    break;
                case 'invite':
                    this.shareBtn.active = true
                    this.descContent.active = true
                    this.descContent.string =  `<color=#5D1F04>累计邀请<color=#ff0000> ${data.conditionValue} </color>个好友\n即可获得<color=#ff0000>【${data.name}】</color> </color>`
                    break;
                case 'restaurantLevel':
                    this.descContent.active = true
                    this.descContent.string = `<color=#5D1F04>升级餐厅等级累计<color=#FF0000>${data.conditionValue}</color>级</color>`

                default:
                    break;
            }
            // this.descContent.string = `邀请1名好友\n即可获得【${data.name}】`
            // this.conditionDesc.active = true
            // this.conditionDesc.getComponent('labelFixedRichText').setNumber('211111111111111', '<color=#5D1F04>需要获得</color><color=#ff0000>', '</color><color=#5D1F04>个金币</color>')
        }
        this.selectCustomer = event.target
        this.selectCustomer.data = data

    },
    shareToFriend() {
        try {
            let setting = {
                title: '你禁得住诱惑吗？',
                imageUrl: 'http://img.wenzhangba.com/allimg/180806/1401-1PP60524130.png',
            }
            let query = `openid=${UserData.openid}&category=customerGettingShare&data=${this.selectCustomer.data.id}&wechatNickname=${UserData.wechatUserInfo.nickName}&wechatAvatarUrl=${UserData.wechatUserInfo.avatarUrl}`

            if (UserData.runtimeState && UserData.runtimeState.shareSettings) {
                let randomIndex = Math.floor(Math.random() * UserData.runtimeState.shareSettings.length)
                setting = UserData.runtimeState.shareSettings[randomIndex]
            }
            setting.query = query

            wx.shareAppMessage(setting)
        } catch (err) {
            console.log(err)
        }
    },
    addBtnToList(obj, atlas) {
        let node = cc.instantiate(this.customerPrefab)

        if (UserData.acquiredCustomersList && UserData.acquiredCustomersList.includes(obj.id)) {
            node.getChildByName('customer').getComponent('ShaderComponent').shader = 0
        } else if (obj.type === 'CHEF') {
            node.getChildByName('customer').getComponent('ShaderComponent').shader = 0
        }

        let btn = node.addComponent(cc.Button)

        obj.atlas = atlas
        var clickEventHandler = new cc.Component.EventHandler();
        clickEventHandler.target = this.node; //这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = "CustomerCollection";//这个是代码文件名
        clickEventHandler.handler = "handleClick";
        clickEventHandler.customEventData = obj
        btn.clickEvents.push(clickEventHandler);

        //因为把角色的资源转换成了Plist 需要切换读取方式
        try {
            let child = node.getChildByName('customer')
            let sp = child.getComponent(cc.Sprite)
            // sp.spriteFrame = this.customerSPAtlas.getSpriteFrame(obj.spriteName)
            sp.spriteFrame = atlas.getSpriteFrame(obj.id)
            this.customerList.addChild(node)
        } catch (err) {
            cc.log("顾客浏览plist载入错误:", err)
        }

    },
    // LIFE-CYCLE CALLBACKS:
    switchShow() {
        // this.customerList.destroyAllChildren()
        this.customerList.removeAllChildren()
        if (this.isShowChef) {
            UserData.runtimeState.chefTypeList.forEach((item) => {
                let d = item.basicData
                this.addBtnToList({name: d.name, id: d.chefID, story: d.description, type: 'CHEF'}, this.chefSPAtlas)
            })
            this.switchText.string = '显示顾客'
        } else {
            CustomerData.LIST.forEach((item) => {
                this.addBtnToList(item, this.customerSPAtlas)
            })
            this.switchText.string = '显示主厨'
        }
        this.isShowChef = !this.isShowChef
    },
    onLoad() {
        this.switchShow()
    },

    start() {
        this.descTitle.string = '点击下方列表查看详情'
    },

    // update (dt) {},
});
